import { useForm } from 'react-hook-form';
import { useState, useEffect, useMemo } from 'react';

import * as z from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useService } from '@flowgram.ai/free-layout-editor';
import { Input } from '@douyinfe/semi-ui';

import { ChatModelType } from '@/typings/chatmodel';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
} from '@/components/ui/form';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';

import { Combobox } from '../../ui/combobox';
import { CustomService } from '../../../services/custom-service';
import { LlmModelSelect } from './llm-modelselect';

// 定义模型属性的验证 schema
const modelPropsSchema = z.object({
  name: z.string().min(1, '模型名称不能为空'),
  type: z.number().int(),
  url: z.string().url(),
  apiKey: z.string().optional(),
  model: z.string().min(1, '大语言模型不能为空'),
  temperature: z.number().min(0, '温度值不能小于0').max(1, '温度值不能大于1'),
  maxTokens: z.number().int().min(1, '最大令牌数不能小于1').max(10000, '最大令牌数不能大于10000'),
  topP: z.number().min(0, 'topP不能小于0').max(1, 'topP不能大于1'),
  frequencyPenalty: z.number().min(-2, '频率惩罚不能小于-2').max(2, '频率惩罚不能大于2'),
  presencePenalty: z.number().min(-2, '存在惩罚不能小于-2').max(2, '存在惩罚不能大于2'),
  enabled: z.boolean(),
});

type ModelProps = z.infer<typeof modelPropsSchema>;

const modelTypes = [
  {
    label: 'Ollama',
    value: 1,
  },
  {
    label: 'OpenAi',
    value: 2,
  },
];

export function LlmPropsSetting({
  model,
  onSaved,
}: {
  model?: ChatModelType;
  onSaved?: () => void;
}) {
  const customService = useService(CustomService);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const newModel = model
      ? {
          // 从ChatModelType转换为ModelProps
          name: model.Name || '',
          type: modelTypes.find((mt) => mt.label === model.ModelType)?.value || 0,
          url: model.ApiUrl || '',
          apiKey: model.ApiKey,
          model: model.ModelName || '',
          temperature: 0.7,
          maxTokens: 1000,
          topP: 1,
          frequencyPenalty: 0,
          presencePenalty: 0,
          enabled: true,
        }
      : {
          // 默认值（包含所有必填字段）
          type: 0,
          name: '',
          url: '',
          apiKey: '',
          model: '',
          temperature: 0.7,
          maxTokens: 1000,
          topP: 1,
          frequencyPenalty: 0,
          presencePenalty: 0,
          enabled: true,
        };
    console.log('model', newModel);
    form.reset(newModel);
  }, [model]);

  // 初始化表单
  const form = useForm<ModelProps>({
    resolver: zodResolver(modelPropsSchema),
    defaultValues: {
      // 默认值（包含所有必填字段）
      type: 0,
      name: '',
      url: '',
      apiKey: '',
      model: '',
      temperature: 0.7,
      maxTokens: 1000,
      topP: 1,
      frequencyPenalty: 0,
      presencePenalty: 0,
      enabled: true,
    },
    mode: 'onSubmit',
    reValidateMode: 'onSubmit',
  });

  // 提交表单
  async function onSubmit(data: ModelProps) {
    console.log('submit data', data);
    setLoading(true);
    const m: ChatModelType = {
      ID: model?.ID || 0,
      Name: form.watch('name'),
      ModelType: modelTypes.find((item) => item.value === form.watch('type'))?.label || '',
      ModelName: form.watch('model'),
      ApiKey: form.watch('apiKey'),
      ApiUrl: form.watch('url'),
      MaxContextLength: 0,
      StreamingEnabled: false,
    };
    try {
      await customService.saveModel(m);
      onSaved?.();
    } catch (error) {
      console.error('保存模型属性失败:', error);
    } finally {
      setLoading(false);
    }
  }

  const typeLabel = useMemo(() => {
    const currentType = form.watch('type');
    return modelTypes.find((item) => item.value === currentType)?.label || '';
  }, [form.watch('type')]);

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>模型属性设置</CardTitle>
        <CardDescription>配置模型的详细参数，包括API密钥和生成选项。</CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>模型名称</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入模型名称" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>模型类型</FormLabel>
                  <FormControl>
                    <Combobox
                      frameworks={modelTypes}
                      defaultValue={1}
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>
                  <FormDescription>选择模型的类型,如ollam、openai等</FormDescription>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="url"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>模型服务地址</FormLabel>
                  <FormControl>
                    <Input placeholder="http://localhost:11343" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="apiKey"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>模型key</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入模型的key" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="model"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>大语言模型</FormLabel>
                  <FormControl>
                    <LlmModelSelect
                      type={typeLabel}
                      uri={form.watch('url')}
                      apiKey={form.watch('apiKey')}
                      chatModel={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
          </form>
        </Form>
      </CardContent>
      <CardFooter className="flex justify-end">
        <Button type="submit" disabled={loading} onClick={form.handleSubmit(onSubmit)}>
          {loading ? '保存中...' : '提交'}
        </Button>
      </CardFooter>
    </Card>
  );
}
